package com.OnTimeTeam.OnTime;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class LabelAutoCompletionIO {

	
	public static void createLabelsFile(String filePath){
		
        try {

        	//filePath paramether - the path of the file (on mobile it's SD card)
            
    		//create file object in the path given
    		File file = new File(filePath);
        	
    		//Only if file doesn't exist - create the labels.xml file and enter the labels node
    		if(file.createNewFile()) {
    			
	        	//Creating an empty XML Document
	
	        	//We need a Document
	        	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	        	DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
	            Document doc = docBuilder.newDocument();
	
	            ////////////////////////
	            //Creating the XML tree
	            
	            doc.normalize();
	
	            //create the root element named labels and add it to the document
	            Element root = doc.createElement("labels");
	            doc.appendChild(root);

	            //Enter some example default labels:
	            
	            Element work = doc.createElement("work");
	            work.setTextContent("Work");
	            root.appendChild(work);
        
	            Element test = doc.createElement("test");
	            test.setTextContent("Test");
	            root.appendChild(test);
	            
	            Element alarm = doc.createElement("alarm");
	            alarm.setTextContent("Alarm");
	            root.appendChild(alarm);
	            
	            Element breakfast = doc.createElement("breakfast");
	            breakfast.setTextContent("Breakfast");
	            root.appendChild(breakfast);	            
	            
	            Element takeABreak = doc.createElement("break");
	            takeABreak.setTextContent("Break");
	            root.appendChild(takeABreak);	 	            
	            
	            /////////////////
	            //Output the XML
	
	            //set up a transformer
	            TransformerFactory transfac = TransformerFactory.newInstance();
	            Transformer trans = transfac.newTransformer();
	            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	            trans.setOutputProperty(OutputKeys.INDENT, "yes");
	
	            //create string from xml tree
	            StringWriter sw = new StringWriter();
	            StreamResult result = new StreamResult(sw);
	            DOMSource source = new DOMSource(doc);
	            trans.transform(source, result);
	            String xmlString = sw.toString();
	    		
	            //Finally - write to the file the node "reminders"
    			FileWriter fStream = new FileWriter(filePath);
    			BufferedWriter out = new BufferedWriter(fStream);
	    		out.write(xmlString);
	    		
	    		//close the file
	    		out.close();
	    		
    		}//end of "if"

        }//end of try block
        catch (Exception e) {//catch any exception
            System.out.println(e);
        }
        
    }//end of method 'createLabelsfile'
	
	public static void addNewLabel(String filePath, String newLabel) {
		
	    try {
	    	
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

            doc.normalize();
                   
            //Get the root of document (reminders node)
            Element labels = doc.getDocumentElement();

            //create new node for the new alarm
            Element newLabelNode = doc.createElement("label");
            newLabelNode.setTextContent(newLabel);
            labels.appendChild(newLabelNode);
      
            /////////////////
            //Change labels.xml file 
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);   
            
        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
	}
	
	public static String[] getAllLabels(String filePath){
		
		//init' Array List of strings (each is label)
		ArrayList<String> labelsStrings = new ArrayList<String>();
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

            //Get the root of document (reminders node)
            Element labelsNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList labels = labelsNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 0; i < labels.getLength() ; i++)
            	if (labels.item(i) instanceof Element) //if the current item is instance of Element node
                    labelsStrings.add(labels.item(i).getTextContent()); //add the String (label) to the arrayList
      

        }//end of try block
        catch (Exception e) {//catch any exception
            System.out.println(e);
        }
        
		String[] labelsToReturn = new String[labelsStrings.size()];
		for(int i = 0; i < labelsStrings.size(); ++i)
			labelsToReturn[i] = labelsStrings.get(i);
		
		return labelsToReturn;
		
    }//end of method 'getAllLabels'	
	
	public static void removeLabel(String filePath, String label) {
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            Element root = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            NodeList labelNodes = root.getChildNodes();
            
            //search for the city
            int i;
            for(i = 0; i < labelNodes.getLength() ; ++i){
            	if (labelNodes.item(i) instanceof Element){
            		if(labelNodes.item(i).getTextContent().equals(label)){
            			labelNodes.item(i).getParentNode().removeChild(labelNodes.item(i));
            			break;
            		}
            	}
            }
            
            doc.normalize();
            
            
            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of XML while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);

		}
		catch (Exception err) {//Catch any Exception
	    	err.printStackTrace();
	    }
	}
	

}//EOF

